package com.ia.aistream.common.type;

import com.alibaba.fastjson.JSONArray;
import com.ia.aistream.common.utils.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author chenjunsheng
 */
@MappedJdbcTypes({JdbcType.VARCHAR})
@MappedTypes({JSONArray.class})
public class JsonArrayTypeHandler extends BaseTypeHandler<JSONArray> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, JSONArray parameter, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, parameter.toJSONString());
    }

    @Override
    public JSONArray getNullableResult(ResultSet rs, String columnName) throws SQLException {
        if(StringUtils.isEmpty(rs.getString(columnName))){
            return null;
        }
        return JSONArray.parseArray(rs.getString(columnName));
    }

    @Override
    public JSONArray getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        if(StringUtils.isEmpty(rs.getString(columnIndex))){
            return null;
        }
        return JSONArray.parseArray(rs.getString(columnIndex));
    }

    @Override
    public JSONArray getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        if (StringUtils.isEmpty(cs.getString(columnIndex))){
            return null;
        }
        return JSONArray.parseArray(cs.getString(columnIndex));
    }
}
